package org.example;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Scanner;

/**
 * 哔哩哔哩音频提取器主程序
 * 演示如何使用BilibiliAudioExtractor提取音频
 */
public class Main {
    private static final Logger logger = LoggerFactory.getLogger(Main.class);
    
    public static void main(String[] args) {
        logger.info("=== 哔哩哔哩音频提取器 ===");
        
        BilibiliAudioExtractor extractor = new BilibiliAudioExtractor();
        Scanner scanner = new Scanner(System.in);

        while (true) {
            System.out.println("\n请选择操作:");
            System.out.println("1. 提取单个视频音频");
            System.out.println("2. 批量提取音频");
            System.out.println("3. 获取视频信息");
            System.out.println("4. 清理下载目录");
            System.out.println("5. 退出");
            System.out.print("请输入选择 (1-5): ");

            String choice = scanner.nextLine().trim();

            try {
                switch (choice) {
                    case "1":
                        extractSingleAudio(extractor, scanner);
                        break;
                    case "2":
                        extractMultipleAudios(extractor, scanner);
                        break;
                    case "3":
                        getVideoInfo(extractor, scanner);
                        break;
                    case "4":
                        cleanupDownloads(extractor);
                        break;
                    case "5":
                        System.out.println("感谢使用！");
                        return;
                    default:
                        System.out.println("无效选择，请重新输入。");
                }
            } catch (Exception e) {
                logger.error("操作过程中发生错误: {}", e.getMessage());
                System.out.println("操作失败: " + e.getMessage());
            }
        }
    }
    
    /**
     * 提取单个视频音频
     */
    private static void extractSingleAudio(BilibiliAudioExtractor extractor, Scanner scanner) {
        System.out.print("请输入哔哩哔哩视频URL: ");
        String url = scanner.nextLine().trim();
        
        if (!extractor.isValidBilibiliUrl(url)) {
            System.out.println("无效的哔哩哔哩URL，请检查格式。");
            return;
        }
        
        System.out.print("请输入输出目录 (直接回车使用默认目录 'downloads'): ");
        String outputPath = scanner.nextLine().trim();
        if (outputPath.isEmpty()) {
            outputPath = "downloads";
        }
        
        try {
            System.out.println("开始提取音频...");
            String result = extractor.extractAudioFromUrl(url, outputPath);
            System.out.println("音频提取成功！文件保存在: " + result);
        } catch (IOException e) {
            System.out.println("音频提取失败: " + e.getMessage());
        }
    }
    
    /**
     * 批量提取音频
     */
    private static void extractMultipleAudios(BilibiliAudioExtractor extractor, Scanner scanner) {
        System.out.println("请输入哔哩哔哩视频URL列表 (每行一个URL，输入空行结束):");
        
        StringBuilder urlsBuilder = new StringBuilder();
        String line;
        while (!(line = scanner.nextLine().trim()).isEmpty()) {
            if (extractor.isValidBilibiliUrl(line)) {
                urlsBuilder.append(line).append("\n");
            } else {
                System.out.println("跳过无效URL: " + line);
            }
        }
        
        if (urlsBuilder.length() == 0) {
            System.out.println("没有输入有效的URL。");
            return;
        }
        
        String[] urls = urlsBuilder.toString().trim().split("\n");
        
        System.out.print("请输入输出目录 (直接回车使用默认目录 'downloads'): ");
        String outputPath = scanner.nextLine().trim();
        if (outputPath.isEmpty()) {
            outputPath = "downloads";
        }
        
        try {
            System.out.println("开始批量提取音频...");
            String[] results = extractor.extractAudioFromUrls(urls, outputPath);
            
            System.out.println("批量提取完成！");
            for (int i = 0; i < results.length; i++) {
                if (results[i] != null) {
                    System.out.println("第 " + (i + 1) + " 个文件: " + results[i]);
                } else {
                    System.out.println("第 " + (i + 1) + " 个文件: 提取失败");
                }
            }
        } catch (IOException e) {
            System.out.println("批量提取失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取视频信息
     */
    private static void getVideoInfo(BilibiliAudioExtractor extractor, Scanner scanner) {
        System.out.print("请输入哔哩哔哩视频URL: ");
        String url = scanner.nextLine().trim();
        
        if (!extractor.isValidBilibiliUrl(url)) {
            System.out.println("无效的哔哩哔哩URL，请检查格式。");
            return;
        }
        
        try {
            BilibiliParser.VideoInfo videoInfo = extractor.getVideoInfo(url);
            System.out.println("\n=== 视频信息 ===");
            System.out.println("标题: " + videoInfo.getTitle());
            System.out.println("BV号: " + videoInfo.getBvid());
            System.out.println("时长: " + formatDuration(videoInfo.getDuration()));
            System.out.println("描述: " + videoInfo.getDescription());
        } catch (IOException e) {
            System.out.println("获取视频信息失败: " + e.getMessage());
        }
    }
    
    /**
     * 清理下载目录
     */
    private static void cleanupDownloads(BilibiliAudioExtractor extractor) {
        System.out.print("确定要清理下载目录吗？(y/N): ");
        Scanner scanner = new Scanner(System.in);
        String confirm = scanner.nextLine().trim().toLowerCase();
        
        if ("y".equals(confirm) || "yes".equals(confirm)) {
            extractor.cleanupDirectory("downloads");
            System.out.println("下载目录已清理。");
        } else {
            System.out.println("操作已取消。");
        }
    }
    
    /**
     * 格式化时长
     */
    private static String formatDuration(long seconds) {
        if (seconds < 60) {
            return seconds + "秒";
        } else if (seconds < 3600) {
            return (seconds / 60) + "分" + (seconds % 60) + "秒";
        } else {
            return (seconds / 3600) + "时" + ((seconds % 3600) / 60) + "分" + (seconds % 60) + "秒";
        }
    }
    
    /**
     * 演示程序入口
     */
    public static void demo() {
        logger.info("=== 哔哩哔哩音频提取器演示 ===");
        
        BilibiliAudioExtractor extractor = new BilibiliAudioExtractor();
        
        // 示例URL（请替换为实际的哔哩哔哩视频URL）
        String demoUrl = "https://www.bilibili.com/video/BV1xx411c7mu";
        
        System.out.println("演示URL: " + demoUrl);
        System.out.println("注意：这是一个演示URL，实际使用时请替换为有效的哔哩哔哩视频URL。");
        
        try {
            // 验证URL
            if (extractor.isValidBilibiliUrl(demoUrl)) {
                System.out.println("URL格式验证通过");
                
                // 获取视频信息
                BilibiliParser.VideoInfo videoInfo = extractor.getVideoInfo(demoUrl);
                System.out.println("视频标题: " + videoInfo.getTitle());
                
                // 提取音频（注释掉以避免实际下载）
                // String result = extractor.extractAudioFromUrl(demoUrl);
                // System.out.println("音频提取完成: " + result);
                
            } else {
                System.out.println("URL格式验证失败");
            }
        } catch (Exception e) {
            logger.error("演示过程中发生错误: {}", e.getMessage());
            System.out.println("演示失败: " + e.getMessage());
        }
    }
}